package com.lwt.codetop.hash;

// 1.两数之和

import java.util.HashMap;
import java.util.Map;

/**
 * 思路：a + b = tar---> 枚举a，判断之前是否出现过b，即是否出现过tar - a ---> 哈希，记录坐标
 */
public class TwoSum {
    public static void main(String[] args) {
        int[] nums = {2,7,11,15};
        int target = 9;
        int[] res = twoSum(nums, target);
        System.out.println(res[0] + " "+ res[1]);
    }

    /**
     * 两数之和
     * @param nums
     * @param target
     * @return
     */
    private static int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        Map<Integer, Integer> cnt = new HashMap<>();
        for (int i = 0; i < n; i++) {
            int x = nums[i];
            if(cnt.containsKey(target - x)){
                return new int[]{cnt.get(target - x), i};
            }
            cnt.put(x, i);
        }

        return new int[0];
    }
}
